<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/12
 * Time: 18:20
 */

namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\WalletLog;
use app\common\model\WalletRecord;
use think\Db;
use app\common\model\Wallet;

class Pay extends Api
{
    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = ['*'];

    public function notify()
    {
        file_put_contents(
            WALLET_ERROR_PATH,
            '【' . date( 'Y-m-d H:i:s', $_SERVER[ 'REQUEST_TIME' ] ) . '】  订单回调通知：'.json_encode($_REQUEST,true). PHP_EOL,
            FILE_APPEND
        );

        $order_sn   = urldecode($_REQUEST['orderid']);//订单号
        $result     = urldecode($_REQUEST['result']);//订单结果
        $amount     = urldecode($_REQUEST['amount']);//订单实际支付金额
        $payamount  = urldecode($_REQUEST['payamount']);//支付金额 单位元
        $systemorderid = urldecode($_REQUEST['systemorderid']);//此次订单过程系统内的订单ID
        $completetime  = urldecode($_REQUEST['completetime']);//订单时间
        $sign = urldecode($_REQUEST['sign']);//md5 签名
        $key  = Config::get('pay.key');
        $sign_str = "orderid=".$order_sn."&result=".$result."&amount=".$amount.
            "&systemorderid=".$systemorderid."&completetime=".$completetime."&key=".$key;//加密源字符串
        $signLocal = md5($sign_str);
        $user_id = WalletRecord::where('record_sn',$order_sn)->value('user_id');
        if( $sign == $signLocal ){
                Db::startTrans();
                try{
                    WalletRecord::where('record_sn',$order_sn)->update([ //修改订单状态
                        'money'         => $amount, //修改为实际支付金额
                        'pay_status'    => 1,//修改支付结果
                        'pay_time'      => time()
                    ]);

                    Wallet::where('user_id',$user_id)->update([ //修改钱包金额
                        'money'     => Db::raw('money+'.$amount),
                    ]);
                    WalletLog::where('record_sn',$order_sn)->update([ //修改订单日志
                        'money' => Wallet::where('user_id',$user_id)->value('money'),
                    ]);

                }catch (\Exception $e){
                    file_put_contents(
                        WALLET_ERROR_PATH,
                        '【' . date( 'Y-m-d H:i:s', $_SERVER[ 'REQUEST_TIME' ] ) . '】  用户{'.$user_id.'}钱包充值失败'.json_encode($e->getMessage()). PHP_EOL,
                        FILE_APPEND
                    );
                    Db::rollback();
                    echo 'fail';
                }
        }else{
            file_put_contents(
                WALLET_ERROR_PATH,
                '【' . date( 'Y-m-d H:i:s', $_SERVER[ 'REQUEST_TIME' ] ) . '】  用户{'.$user_id.'}签名错误'. PHP_EOL,
                FILE_APPEND
            );
            Db::rollback();
            echo 'fail';
        }
    }
}